<?php 

/**
* 分页类
*/
class Page 
{
	public $total;//总条数
	public $num;//每页显示多少条
	public $pages;//总页数
	public $less;//少于多少页需要走不同的逻辑
	public $current = 1; //当前页码
	public $start =0; //从第几个开始取
	public $limit;//取几个,
	
	//构造方法
	function __construct($total,$num,$less=5)
	{

		$this->total=$total;

		$this->num=$num;

		$this->less=$less;

		$this->pages =ceil($total/$num);
		
		$this->current = isset($_GET['p'])?$_GET['p']:1;
		if($this->current>$this->pages){
			$this->current=$this->pages;
		}
		$this->limit=$num;
		$this->start=($this->current-1)*$num;
	}

	//输出分页
	public function show()
	{
		// 判断输出的格式，低于less,全部显示
		if($this->pages<=$this->less){
			return $this->_less();
		}else{
			return $this->_more();
		}
	}

	//小于规定的页数，直接显示
	public function _less(){

		$str = "";

		for ($i=1; $i <=$this->pages ; $i++) { 
			if($i == $this->current){
				$str .= "<a class='current' href='./index.php?p=".$i."'>".$i."</a>";
			}else{
				$str .= "<a href='./index.php?p=".$i."'>".$i."</a>";
			}
			
		}

		return $str;
	}

	//超过5页的显示效果
	public function _more()
	{
		// 当前页码小于总显示页码
		if($this->current<$this->less){

			$str = '';
			for ($i=1; $i < $this->less; $i++) { 
				if($i == $this->current){
				$str .= "<a class='current' href='./index.php?p=".$i."'>".$i."</a>";
				}else{
					$str .= "<a href='./index.php?p=".$i."'>".$i."</a>";
				}
			}

			$str .="<a class='next' href='./index.php?p=".($this->current+1)."'>下一页</a>";

			return $str;
			// 当前页码等于总页码
		}elseif($this->current == $this->pages){

			$str = '';

			$str .="<a class='next' href='./index.php?p=".($this->current-1)."'>上一页</a>";

			for ($i=$this->current-4; $i <= $this->current; $i++) { 
				if($i == $this->current){
				$str .= "<a class='current' href='./index.php?p=".$i."'>".$i."</a>";
				}else{
					$str .= "<a href='./index.php?p=".$i."'>".$i."</a>";
				}
			}

			return $str;

		}elseif($this->current>=$this->less){

			$str = '';

			$str .="<a class='next' href='./index.php?p=".($this->current-1)."'>上一页</a>";

			for ($i=$this->current-2; $i <= $this->current+2; $i++) { 
				if($i == $this->current){
				$str .= "<a class='current' href='./index.php?p=".$i."'>".$i."</a>";
				}else{
					$str .= "<a href='./index.php?p=".$i."'>".$i."</a>";
				}
			}

			$str .="<a class='next' href='./index.php?p=".($this->current+1)."'>下一页</a>";

			return $str;

		}
	}
}









 ?>